import React, { useState } from 'react';
import { Document } from "langchain/document";
import { RecursiveCharacterTextSplitter } from "langchain/text_splitter";
// 导入浏览器专用版本的pdf-parse
import { PDFLoader } from "@langchain/community/document_loaders/fs/pdf";
import './document.less';

interface DocumentProps {}

const DocumentPage: React.FC<DocumentProps> = () => {
  const [uploadedFile, setUploadedFile] = useState<File | null>(null);
  const [documents, setDocuments] = useState<Document[]>([]);
  const [isProcessing, setIsProcessing] = useState<boolean>(false);
  const [error, setError] = useState<string | null>(null);
  const [dragActive, setDragActive] = useState<boolean>(false);

  // 处理PDF解析和分割（纯浏览器实现）
  const processPdfFile = async (file: File) => {
    setIsProcessing(true);
    setError(null);
    setDocuments([]);

    try {
      const loader = new PDFLoader(file);
      const docs = await loader.load();

      // 创建文档对象
      const doc = new Document({
        pageContent: docs.map(d => d.pageContent).join('\n'), // 合并所有页面内容
        metadata: {
          source: file.name,
          pages: docs.length, // 使用数组长度作为页数
          fileType: file.type,
          fileSize: file.size
        }
      });
      // 创建文本分割器
      const splitter = new RecursiveCharacterTextSplitter({
        chunkSize: 50,
        chunkOverlap: 10,
      });
      // 分割文档
      const splitDocs = await splitter.splitDocuments([doc]);
      setDocuments(splitDocs);

    } catch (err) {
      console.error('文档处理错误:', err);
      setError(err instanceof Error ? err.message : '文档处理失败，请重试');
    } finally {
      setIsProcessing(false);
    }
  };

  // 处理文件上传
  const handleFileUpload = (file: File) => {
    if (!file.name.endsWith('.pdf')) {
      setError('请上传PDF格式的文件');
      return;
    }
    setUploadedFile(file);
    processPdfFile(file);
  };

  // 处理文件选择
  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      handleFileUpload(e.target.files[0]);
    }
  };

  // 拖放处理
  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    setDragActive(true);
  };

  const handleDragLeave = () => {
    setDragActive(false);
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    setDragActive(false);
    if (e.dataTransfer.files && e.dataTransfer.files[0]) {
      handleFileUpload(e.dataTransfer.files[0]);
    }
  };

  const handleRemoveFile = (e) => {
    e.preventDefault();
    e.stopPropagation();
    console.log('Removing file');
    setUploadedFile(null);
    setError('');
    setDocuments([]);
    setIsProcessing(false);
  };

  return (
    <div className="document-container">
      <h2>文档上传分段</h2>

      {/* 文件上传区域 */}
      <div 
        className={`upload-section ${dragActive ? 'drag-active' : ''} ${uploadedFile ? 'has-file' : ''}`}
        onDragOver={handleDragOver}
        onDragLeave={handleDragLeave}
        onDrop={handleDrop}
      >
        <input
          type="file"
          accept=".pdf"
          onChange={handleFileChange}
          className="file-input"
        />
        
        <div className="upload-content">
          <div className="upload-icon">📄</div>
          <div className="upload-text">
            {uploadedFile ? (
              <div className="file-info">
                <span className="file-name">{uploadedFile.name}</span>
                <button onClick={handleRemoveFile} className="remove-btn">×</button>
              </div>
            ) : (
              <>点击上传或拖放PDF文件到此处</>
            )}
          </div>
          <div className="upload-hint">支持最大10MB的PDF文件</div>
        </div>
      </div>

      {/* 处理状态 */}
      {isProcessing && (
        <div className="processing-status">正在处理文档，请稍候...</div>
      )}

      {/* 错误信息 */}
      {error && (
        <div className="error-message">{error}</div>
      )}

      {/* 文档内容展示 */}
      {documents.length > 0 && (
        <div className="documents-section">
          <h3>分割后的文档内容 ({documents.length} 段)</h3>
          <div className="documents-list">
            {documents.map((doc, index) => (
              <div key={index} className="document-chunk">
                <div className="chunk-header">
                  段落 {index + 1} - 来源: {doc.metadata.source}
                </div>
                <div className="chunk-content">
                  {doc.pageContent}
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
};

export default DocumentPage;